package controllers

import (
	"acs/management/models"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"strconv"

	"github.com/labstack/echo"
)

//获取
func GetLogHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	operationIDStr := c.Param("id")
	operationID, swtichErr := strconv.Atoi(operationIDStr)
	models.CheckError(swtichErr)
	currentUser := models.CheckLogin(c)
	_, err = models.CheckUserPrivilege(&currentUser, models.TableLog, operationID, models.RoleRead)
	models.CheckError(err)
	oldInDB, dbErr := models.GetTLogById(int64(operationID))
	models.CheckError(dbErr)
	c.JSON(http.StatusOK, oldInDB)
	return
}

//获取列表
func ListLogHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	requestbody, requesterr := ioutil.ReadAll(c.Request().Body)
	models.CheckError(requesterr)
	currentPageStr := c.Param("page")
	currentPage, switchErr := strconv.Atoi(currentPageStr)
	models.CheckError(switchErr)
	currentStepStr := c.Param("step")
	currentStep, switchErr2 := strconv.Atoi(currentStepStr)
	models.CheckError(switchErr2)
	if currentPage < 1 || currentStep < 1 {
		panic(errors.New("参数不符合标准。"))
	}

	type receiveData struct {
		NickName string `json:"nick_name"`
		LogType  string `json:"log_type"`
	}
	var currentData receiveData
	err = json.Unmarshal(requestbody, &currentData)
	models.CheckError(err)
	currentUser := models.CheckLogin(c)
	allowList, checkerr := models.CheckUserPrivilege(&currentUser, models.TableLog, 0, models.RoleRead)
	models.CheckError(checkerr)
	query := make(map[string]interface{})
	if len(allowList) == 1 && allowList[0] == 0 {
		// 可以拿到全部的数据
	} else {
		query["id__in"] = allowList
	}
	if currentData.LogType != "" && currentData.LogType != "0" {
		query["log_type"] = currentData.LogType
	}
	if currentData.NickName != "" {
		query["user_nickname__contains"] = currentData.NickName
	}
	datalist, totalNum, listErr := models.GetAllTLog(query, nil, []string{"id"}, []string{"desc"}, int64((currentPage-1)*currentStep), int64(currentStep), true)
	models.CheckError(listErr)
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, currentUser, datalist, totalNum))
	return
}
